package com.angel.bo.auth.client.interceptor;


import com.angel.bo.auth.client.annotation.IgnoreUserToken;
import com.angel.bo.auth.client.jwt.AuthUtil;
import com.angel.bo.auth.client.properties.AuthProperties;
import com.angel.bo.beans.jwt.JwtInfo;
import com.angel.bo.common.context.CommonContextHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Haibo.Mei [Haibo.Mei@ge.com]
 * @Description: 用户权限拦截器
 * @Date: 10:08 2018/1/30
 */
public class UserAuthInterceptor extends HandlerInterceptorAdapter{

    @Autowired
    private AuthUtil authUtil;

    @Autowired
    private AuthProperties authProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final String errorPage = "/error";
        /*
         * 如果不用验证token则
         */
        if(!authProperties.isEnable()){
            return super.preHandle(request, response, handler);
        }
        /*
         * 跳转到错误页面时，不拦截
         */
        if(request.getRequestURL().toString().contains(errorPage)){
            return super.preHandle(request, response, handler);
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 配置该注解，说明不进行用户拦截
        IgnoreUserToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreUserToken.class);
        if (annotation == null) {
            annotation = handlerMethod.getMethodAnnotation(IgnoreUserToken.class);
        }
        if(annotation!=null) {
            return super.preHandle(request, response, handler);
        }
        String token = request.getHeader(authProperties.getTokenHeader());
        //开始校验token
        JwtInfo jwtInfo = authUtil.getJwtFromToken(token);
        CommonContextHandler.setToken(token);

        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CommonContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
